'''
Author: xiaonancheng
Date: 2023-03-05 15:58:59
https://www.cnblogs.com/xiaonancheng
Copyright (c) 2023 by @xiaonancheng, All Rights Reserved. 
'''
from django.shortcuts import render,redirect
from django.http import HttpResponse,JsonResponse
from django.core.paginator import Paginator

from .models import User,Health_doc,Relative,Userinfo,PEinfo,Visit
from django.http import HttpResponseRedirect
from DoctorApp.models import Doctor,Register,Department,Consult
from BlogApp.models import News,Post,Comment
def login_role_auth(fn):
    def wrapper(request,*args,**kwargs):
        if request.session.get('is_login', False) and request.session.get('user_type')=="/user" :
            return fn(request,*args,*kwargs)
        else:
            # 获取用户当前访问的url，并传递给/user/login/
            next = request.get_full_path() 
            request.session["is_login"]=False
            red = HttpResponseRedirect("/login/?"+next)
            return red
    return wrapper

# Create your views here.
@login_role_auth
def change_pwd(request):#个人中心 修改密码
    massage={"info":''}
    if request.method=="POST":
        old_pwd=request.POST.get("old_pwd")
        new_pwd=request.POST.get("new_pwd")
        if old_pwd==new_pwd:
            massage={"info":'新密码和原密码一致',"res":0}
        else:
            user=User.objects.filter(uid=request.session.get('uid')).first()
            if user.password!=old_pwd:
                massage={"info":'原密码不正确',"res":1}
            else:
                user.password=new_pwd
                user.save()
                massage={"info":'密码修改成功',"res":2}

    
    return JsonResponse(massage) 
@login_role_auth
def personal_info(request):#个人中心 个人信息
    user=User.objects.filter(uid=request.session.get('uid')).first()
    infos=Userinfo.objects.filter(uid=user).order_by('-c_time')
    nui=infos.first()#最新个人信息
    

    return render(request,"user_index.html",{"user":user,'nui':nui})

@login_role_auth
def user_basic(request):#个人中心 个人基本信息

    user=User.objects.filter(uid=request.session.get('uid')).first()
    return render(request,"user_basic.html",{"user":user})
@login_role_auth
def health_archives(request):#档案管理
    if request.method=="GET":
        health_doc=Health_doc.objects.filter(uid=request.session.get("uid"))
        return render(request,".html",{"health_doc":health_doc})
    if request.method=="POST":
        pass
def personal_add(request):#个人档案添加
    user=User.objects.filter(uid=request.session.get('uid')).first()
    if request.method=="POST":
        type=request.POST.get("type")
        id=request.POST.get("id")
        if type=="info":
            ui = Userinfo.objects.filter(infoid=id).first() if id else  Userinfo()
            # ui=Userinfo()

            ui.uid=user
            user_name=request.POST.get("user_name")
            user.user_name=user_name
            ui.user_name=user_name
            user_sex=request.POST.get("user_sex")
            user.user_sex=user_sex
            ui.user_sex=user_sex
            user_age=request.POST.get("user_age")
            user.user_age=user_age
            ui.user_age=user_age
            user_height=request.POST.get("user_height")
            ui.user_height=user_height
            user_weight=request.POST.get("user_weight")
            ui.user_weight=user_weight
            allergy=request.POST.get("allergy")
            ui.allergy=allergy

            illness=request.POST.get("illness")
            ui.illness=illness
            disability=request.POST.get("disability")
            ui.disability=disability

            common_drugs=request.POST.get("common_drugs")
            ui.common_drugs=common_drugs
            if not id:
                user.save()
            ui.save()
            
            return redirect("/user/personal_manage/")
        elif type=="PE":
            # p=PEinfo()
            p = PEinfo.objects.filter(PEid=id).first() if id else  PEinfo()

            p.uid=user

            # user_name=request.POST.get("user_name")
            p.user_name=user.user_name

            # user_sex=request.POST.get("user_sex")
            p.user_sex=user.user_sex

            hospital=request.POST.get("hospital")
            p.hospital=hospital

            items=request.POST.get("items",'')
            p.items=items

            blood_sugar=request.POST.get("blood_sugar")
            p.blood_sugar=blood_sugar

            total_cholesterol=request.POST.get("total_cholesterol")
            p.total_cholesterol=total_cholesterol

            triglyceride=request.POST.get("triglyceride")
            p.triglyceride=triglyceride

            minimum=request.POST.get("minimum")
            p.minimum=minimum

            maximum=request.POST.get("maximum")
            p.maximum=maximum

            heart_rate=request.POST.get("heart_rate")
            p.heart_rate=heart_rate
            date=request.POST.get("date")
            p.date=date

            p.save()

            return redirect("/user/personal_manage/")
            
        elif type=="visit":
            # v=Visit()
            v = Visit.objects.filter(vid=id).first() if id else  Visit()

            v.uid=user

            # user_name=request.POST.get("user_name")
            v.user_name=user.user_name

            # user_sex=user.request.POST.get("user_sex")
            v.user_sex=user.user_sex

            department=request.POST.get("department")
            v.department=department

            chief_complaint=request.POST.get("chief_complaint")
            v.chief_complaint=chief_complaint

            HPI=request.POST.get("HPI")
            v.HPI=HPI

            PH=request.POST.get("PH")
            v.PH=PH

            diagnose=request.POST.get("diagnose")
            v.diagnose=diagnose

            prescription=request.POST.get("prescription")
            v.prescription=prescription

            DA=request.POST.get("DA")
            v.DA=DA

            date=request.POST.get("date")
            v.date=date

            v.save()

            return redirect("/user/personal_manage/")
            
            

    return render(request,"personal_add.html",{"user":user,'active_menu':'personal_add'})
@login_role_auth
def personal_manage(request):#个人健康档案管理
    user=User.objects.filter(uid=request.session.get('uid')).first()
    if request.method=="GET":
        t=request.GET.get("type")
        i=request.GET.get("id")
        change=request.GET.get("change")
        if t and not change:
            if t=="info":
                info=Userinfo.objects.filter(infoid=i).first()
                info.delete()
            if t=="visit":
                v=Visit.objects.filter(vid=i).first()
                v.delete()
            if t=="PE":
                p=PEinfo.objects.filter(PEid=i).first()
                p.delete()
            return redirect("/user/personal_manage/")
        elif t and change:
            if t=="info":
                info=Userinfo.objects.filter(infoid=i).first()
                return render(request,"change_info.html",{"info":info,'active_menu':'personal_manage'})
            if t=="visit":
                v=Visit.objects.filter(vid=i).first()
                return render(request,"change_visit.html",{"v":v,'active_menu':'personal_manage'})
            if t=="PE":
                p=PEinfo.objects.filter(PEid=i).first()
                return render(request,"change_PE.html",{"p":p,'active_menu':'personal_manage'})
            pass

        infos=Userinfo.objects.filter(uid=user).order_by('-c_time')
        nui=infos.first()#最新个人信息
        PEs=PEinfo.objects.filter(uid=user).order_by('-c_time')#体检信息
        vs=Visit.objects.filter(uid=user).order_by('-c_time')#就诊记录
        

        return render(request,"personal_manage.html",{"user":user,"nui":nui,"infos":infos,'PEs':PEs,"vs":vs,'active_menu':'personal_manage'})
    elif request.method=="POST":
        iid=request.POST.get("iid")
        if iid:
            ui=Userinfo.objects.filter(infoid=iid).first()
        else:
            ui=Userinfo()
        ui.uid=user
        user_name=request.POST.get("user_name")
        user.user_name=user_name
        ui.user_name=user_name
        user_sex=request.POST.get("user_sex")
        user.user_sex=user_sex
        ui.user_sex=user_sex
        user_age=request.POST.get("user_age")
        user.user_age=user_age
        ui.user_age=user_age
        user_height=request.POST.get("user_height")
        ui.user_height=user_height
        user_weight=request.POST.get("user_weight")
        ui.user_weight=user_weight
        allergy=request.POST.get("allergy")
        ui.allergy=allergy

        illness=request.POST.get("illness")
        ui.illness=illness
        disability=request.POST.get("disability")
        ui.disability=disability
        id_no=request.POST.get("id_no")
        phone=request.POST.get("phone")
        user.id_no=id_no
        user.phone=phone

        common_drugs=request.POST.get("common_drugs")
        ui.common_drugs=common_drugs

        ui.save()
        user.save()
        return redirect("/user/personal_manage/")

@login_role_auth
def family_add(request):#家庭健康档案添加
    if request.method=="POST":
        user=User.objects.filter(uid=request.session.get('uid')).first()
        relative=Relative()
        relative.uid=user
        relative.relationship=request.POST.get('relationship')
        relative.relative_name=request.POST.get('relative_name')
        relative.relative_sex=request.POST.get('relative_sex')
        relative.relative_age=request.POST.get('relative_age')
        relative.relative_height=request.POST.get('relative_height')
        relative.relative_weight=request.POST.get('relative_weight')
        relative.relative_allergy=request.POST.get('relative_allergy')
        relative.relative_illness=request.POST.get('relative_illness')
        relative.disability=request.POST.get('disability')
        relative.relative_surgery=request.POST.get('relative_surgery')
        relative.relative_injury=request.POST.get('relative_injury')
        relative.common_drugs=request.POST.get('common_drugs')
        relative.save()
        return redirect("/user/family_manage/")

    return render(request,"family_add.html",{'active_menu':'family_add'})
@login_role_auth
def family_manage(request):#家庭健康档案管理
    if request.method=="GET":

        relatives=Relative.objects.filter(uid=request.session.get('uid'))
        # print(relatives)
        rid=request.GET.get('rid')
        # print(rid)
        if rid:
            relative=Relative.objects.filter(id=rid).first()
        else:
            relative=relatives.first() if relatives else None
        if request.GET.get('type'):
            relative.delete()
            return redirect(f"/user/family_manage/")

        return render(request,'family_manage.html',{'active_menu':'family_manage','relatives':relatives,'relative':relative,'rid':relative.id if relative else None})
    elif request.method=="POST":
        rid=request.POST.get('rid')
        user=User.objects.filter(uid=request.session.get('uid')).first()
        
        
        if rid :
            relative= Relative.objects.filter(id=rid).first() 
        else:
            relative=Relative()
            relative.uid=user
        relative.relative_name=request.POST.get('relative_name')
        relative.relative_sex=request.POST.get('relative_sex')
        relative.relative_age=request.POST.get('relative_age')
        relative.relative_height=request.POST.get('relative_height')
        relative.relative_weight=request.POST.get('relative_weight')
        relative.relative_allergy=request.POST.get('relative_allergy')
        relative.relative_illness=request.POST.get('relative_illness')
        relative.disability=request.POST.get('disability')
        relative.relative_surgery=request.POST.get('relative_surgery')
        relative.relative_injury=request.POST.get('relative_injury')
        relative.common_drugs=request.POST.get('common_drugs')
        relative.save()
        return redirect(f"/user/family_manage/?rid={relative.id}")
        


@login_role_auth
def online_consult(request):#线上咨询
    if request.method=="GET":
        did=request.GET.get("did")
        deid=request.GET.get("deid")
        if did:
            doctor=Doctor.objects.filter(uid=did).first()
            return render(request,"symptom.html",{"doctor":doctor})
        if deid:
            doctors=Doctor.objects.filter(deid=deid)
            de=Department.objects.filter(id=deid).first()
            # deid=request.GET.get("deid")
        else:
            doctors=Doctor.objects.all()
            de=[]
        departments=Department.objects.all()
        # doctors=Doctor.objects.all()
        return render(request,"choose_doctor.html",{"doctors":doctors,"departments":departments,'de':de,'active_menu':'online_consult'})
        
        
        # return render(request,"online_consult.html",{"doctors":doctors,"departments":departments})
    elif request.method=="POST":
        did=request.POST.get("did")#医生编号
        target=request.POST.get("target")#目标
        howlong=request.POST.get("howlong")#持续时间
        drugs=request.POST.get("drugs")#药品
        con=Consult()
        print(did)
        con.d_id=Doctor.objects.filter(uid=did).first()
        print(request.session.get("uid"))
        con.u_id=User.objects.filter(uid=request.session.get("uid")).first()
        con.target=target
        con.howlong=howlong
        con.drugs=drugs
        con.state=0
        con.save()
        return redirect("/user/my_online_consult/")
@login_role_auth
def my_online_consult(request):#我的线上咨询
    if request.method=="GET":
        cid=request.GET.get('cid')
        delete=request.GET.get('delete')
        if cid and not delete:
            c=Consult.objects.filter(c_id=cid).first()
            return render(request,"prescription_detail.html",{'c':c})
        elif cid and  delete:
            c=Consult.objects.filter(c_id=cid).first()
            # print(1)
            c.delete()

            return redirect("/user/my_online_consult/")
        consults=Consult.objects.filter(u_id=User.objects.filter(uid=request.session.get("uid")).first())
        return render(request,"my_online_consult.html",{'consults':consults,"active_menu":'my_online_consult'})      

@login_role_auth
def register_online(request):#线上挂号
    if request.method=="GET":
        doctors=Doctor.objects.all().values()
        departments=Department.objects.all()
        rid=request.GET.get("rid")
        doc=[]
        # print(doctors)
        for i in doctors:
            doc.append({'uid':i["uid"],'doctor_name':i["doctor_name"],'title':i['title'],"department":i['deid_id'],'hospital':i['hospital']})
        user=User.objects.filter(uid=request.session.get("uid")).first()
        if rid:
            r=Register.objects.filter(r_id=rid).first()
            return render(request,"register_online_change.html",{"doctors":doc,"user":user,"departments":departments,'r':r,'active_menu':'register_online'})
        time_range=['8:00-8:30','8:30-9:00','9:00-9:30','10:00-10:30','10:30-11:00','11:30-12:00','14:00-14:30','14:30-15:00','15:00-15:30','15:30-16:00','16:00-16:30','16:30-17:00']
        return render(request,"register_online.html",{"doctors":doc,"user":user,"departments":departments,'active_menu':'register_online','time_range':time_range})
    elif request.method=="POST":
        user_id=request.POST.get("uid")
        
        d_id=request.POST.get("d_id")
        # print(user_id,d_id)

        r_type=request.POST.get("r_type")
        date=request.POST.get("date")
        s_time=request.POST.get("s_time")
        change=request.POST.get("change")
        if change:
            re=Register.objects.filter(r_id=change).first()
        else:
            re=Register()
        re.d_id=Doctor.objects.filter(uid=d_id).first()
        
        re.u_id=User.objects.filter(uid=user_id).first()
        re.r_type=r_type
        re.date=date
        t_rang=s_time.split('-')
        re.s_time=t_rang[0]
        re.end_time=t_rang[1]
        re.save()
        return redirect("/user/user_register/")
def user_register(request):#我的预约
    if request.method=="GET":
        rid=request.GET.get('rid')
        if rid:
            r=Register.objects.filter(r_id=rid).first()
            r.delete()
            
            return redirect("/user/user_register/")
        my_re=Register.objects.filter(u_id=User.objects.filter(uid=request.session.get("uid")).first())
    
        return render(request,"user_register.html",{"my_re":my_re,'active_menu':'user_register'}) 
    # elif request.method=="POST":

    #     pass
@login_role_auth
def news(request):#知识科普 新闻
    p=request.GET.get('p',1)
    size=request.GET.get("size",5)
    q=request.GET.get('q')
    if request.method=="GET" and not q:

        page_obj=Paginator(News.objects.all(),size)
        news=page_obj.get_page(p)

        return render(request,"news.html",{"news":news,'active_menu':'news'})
    elif request.method=="GET" and q:
        page_obj=Paginator(News.objects.filter(news_title__contains=q),size)
        news=page_obj.get_page(p)

        return render(request,"news.html",{"news":news,'active_menu':'news','q':q})
def news_details(request):#新闻详情
    n_id=request.GET.get("nid")
    if request.method=="GET" and n_id:
        
        news=News.objects.filter(news_id=n_id).first()

        return render(request,"news_details.html",{"news":news})
    else:
        return redirect("/error/")
    
@login_role_auth
def blog(request):#论坛 增删查改
    q=request.GET.get('q')
    if request.method=="GET" and not q:
        page=request.GET.get("page",1)
        user=User.objects.filter(uid=request.session.get("uid")).first()
        posts=Post.objects.all()
        return render(request,"discuss.html",{"posts":posts,'user':user})
    elif request.method=="GET" and  q:
        user=User.objects.filter(uid=request.session.get("uid")).first()
        posts=Post.objects.filter(post_title__contains=q)
        return render(request,"discuss.html",{"posts":posts,'user':user,'q':q})
    elif request.method=="POST":
        type=request.POST.get("type")
        if type=="add":
            title=request.POST.get("title","")
            content=request.POST.get("content","")
            post_type=request.POST.get("post_type","")
            p=Post()
            p.post_title=title
            p.post_content=content
            p.post_type=post_type
            p.u_id=User.objects.filter(uid=request.session.get("uid")).first()
            p.save()
            return redirect("/user/blog/")#JsonResponse({"status":"200","info":"ok"})
        elif type=="delete":
            p_id=request.POST.get("pid",None)
            p=Post.objects.filter(post_id=p_id).first()
            if p.u_id==User.objects.filter(uid=request.session.get("uid")).first():
                p.delete()
            else:
                return JsonResponse({"state":400,"info":"error"})
            return JsonResponse({"state":200,"info":"ok"})
            
            # return redirect("/user/blog/")#JsonResponse({"status":"200","info":"ok"})
        elif type=="change":
            p_id=request.POST.get("pid",None)
            title=request.POST.get("title","")
            content=request.POST.get("content","")
            post_type=request.POST.get("post_type","")
            p=Post.objects.filter(p_id).first()
            p.post_title=title
            p.post_content=content
            p.post_type=post_type
            p.save()
            return JsonResponse({"state":200,"info":"ok"})

@login_role_auth        
def like_post(request):#点赞/取消点赞帖子
    try:
        user =User.objects.filter(uid=request.session.get("uid")).first()
        pid = request.POST.get('pid')
        p=Post.objects.filter(post_id=pid).first()
        if p:
            user_like = p.users_like.filter(uid=user.uid).first()
            # 查询当前用户是否为当前文章点过赞
            type = 1
            if user_like:
                # 点赞过
                type = 0
                p.users_like.remove(user)
            else:
                #没点赞
                p.users_like.add(user)
            like_sum=p.users_like.count()
            return JsonResponse({'state': 200, 'type': type, 'like_sum': like_sum})
        else:
            return JsonResponse({'state': 400, 'data': '点赞无效'})
    except Exception as e:
        return JsonResponse({'state': 500, 'data': f'出现异常：{e}'})
    
@login_role_auth
def blog_details(request):#博客详情
    p_id=request.GET.get("pid",None)
    if request.method=="GET" and p_id:
        
        post=Post.objects.filter(post_id=p_id).first()
        comments=Comment.objects.filter(p_id=post)
        return render(request,"post.html",{"post":post,'comments':comments})
    else:
        return redirect("/error/")

@login_role_auth
def comment(request):#评论
    post_id=request.GET.get("pid")
    if request.method=="GET" and post_id:
        comments=Comment.objects.filter(p_id=post_id)
        return render(request,"comments.html",{"comments":comments})
    elif request.method=="POST":
        comment=Comment()
        content=request.POST.get("content","")
        comment.content=content
        p_id=request.POST.get("pid",None)
        p=Post.objects.filter(post_id=p_id).first()
        comment.p_id=p
        comment.u_id=User.objects.filter(uid=request.session.get("uid")).first()
        comment.save()
        return redirect("/user/blog/")#JsonResponse({"status":"200","info":"ok"})
from UserApp.QA.kbqa_test import KBQA
@login_role_auth    
def answer(request):#疾病知识问答系统
    if request.method=="POST":
        question=request.POST.get('msg')
        try:
            handler = KBQA()
            answer=''
            print(1111)
            print(question)
            if  question:
                answer=handler.qa_main(question)
        except Exception as e:
            print(e)
            answer= "对不起，您的问题我不知道，我今后会努力改进的。"
        return JsonResponse({'answer':answer})
    return render(request,"answer.html",{'active_menu':'answer'})


